from django.http import HttpResponse
from django_redis import get_redis_connection
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from libs.captcha.captcha import captcha
from verifications.serializers import RegiserSMSCodeSerializer


class RegisterImageCodeView(APIView):
    def get(self,request,image_code_id):
        # 后端接收uuid
        # 通过第三方库, 生成图片和验证码, 我们需要对验证码进行redis保存
        # 思路为:
        # 创建图片和验证码
        # 通过redis进行保存验证码, 需要在设置中添加
        # 验证码数据库选项
        # 将图片返回
        text,image=captcha.generate_captcha()
        # 连接redis
        redis_conn=get_redis_connection('code')
        # 保存数据
        redis_conn.setex('img_%s'%image_code_id,60,text)
        # return Response(image,content_type='image/jpeg')
        return HttpResponse(image,content_type='image/jpeg')


class RegiserSMSCodeView(GenericAPIView):
    # GET / verifications / smscodes / (?P < mobile > 1[345789]\d
    # {9}) / ?text = xxxx & image_code_id = xxxx
    def get(self,request,mobile):
        # 获取后段数据
        query_params=request.query_params
        # 实例化序列化器,校验数据
        # 创建序列化器, 定义text
        # 和image_code_id,redis
        serializer=RegiserSMSCodeSerializer(data=query_params)
        serializer.is_valid(raise_exception=True)

        # 判断该用户是否频繁获取
        # 生成短信验证码
        import random
        sms_code='%06d'%random.randint(0,999999)
        # redis增加记录
        redis_conn=get_redis_connection('code')
        redis_conn.setex('sms_%s'%mobile,300,sms_code)
        # 发送短信
        # ccp.send_template_sms('18516952650', ['1234', 5], 1)
        # 同步发送短信验证码
        # CCP().send_template_sms(mobile,[sms_code,5],1)
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile,sms_code)

        # 返回响应
        return Response({'message':'ok'})
        pass

